/**
 *  创建打开数据库
 * @param {String} dbName 数据库名字
 * @param {Number} version 版本
 * @returns {Promise} 返回Promise对象
 */
export function openDB (dbName, version = 1) {
  return new Promise((resolve, reject) => {
    let db
    // 打开数据库，若没有则会创建
    const request = window.indexedDB.open(dbName, version)
    request.onsuccess = function (event) {
      db = event.target.result // 数据库对象
      console.log('数据库打开成功', event)
      resolve(db)
    }
    request.onerror = function (event) {
      console.log('数据库打开失败', event)
      reject(event)
    }
    request.onupgradeneeded = function (event) {
      // 如果有升级，会先执行升级回调函数，再执行success函数
      console.log('数据库升级', event)
      db = event.target.result
      // 创建表
      if (!db.objectStoreNames.contains('log')) {
        const objectStore = db.createObjectStore('log', {
          autoIncrement: true // 设置主键自增
        })
        // 创建索引
        objectStore.createIndex('isUpload', 'isUpload', { unique: false })
        objectStore.createIndex('errorMessage', 'errorMessage', { unique: false })
        objectStore.createIndex('type', 'type', { unique: false })
        objectStore.createIndex('robot', 'robot', { unique: false })
        objectStore.createIndex('date', 'date', { unique: false })
      }
    }
  })
}

/**
 * 新增数据
 * @param {object} db 数据库实例
 * @param {string} storeName 仓库名称
 * @param {string} data 数据
 */
export function insertData (db, storeName, data) {
  return new Promise((resolve, reject) => {
    const request = db
      .transaction([storeName], 'readwrite') // 事务对象 指定表格名称和操作模式（"只读"或"读写"）
      .objectStore(storeName) // 仓库对象
      .add(data)

    request.onsuccess = function (event) {
      console.log('数据写入成功')
      resolve(db)
    }

    request.onerror = function (event) {
      console.log('数据写入失败')
      reject(db)
    }
  })
}

/**
 * 更新数据
 * @param {object} db 数据库实例
 * @param {string} storeName 仓库名称
 * @param {object} data 数据
 */
export function updateDB (db, storeName, data) {
  return new Promise((resolve, reject) => {
    const request = db
      .transaction([storeName], 'readwrite') // 事务对象
      .objectStore(storeName) // 仓库对象
      .put(data)

    request.onsuccess = function () {
      console.log('数据更新成功')
      resolve('数据更新成功')
    }

    request.onerror = function () {
      console.log('数据更新失败')
      reject('数据更新失败')
    }
  })
}

/**
 * 关闭数据库
 * @param {object} db 数据库实例
 */
export function closeDB (db) {
  db.close()
}

export function deleteData (db, storeName) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction(['log'], 'readwrite')
    const store = transaction.objectStore('log')

    // 获取索引
    const index = store.index('date')
    const request = index.openCursor()

    // 获取当前时间的时间戳
    const currentDate = new Date().getTime()

    // 处理游标项
    request.onsuccess = function (event) {
      console.log('成功回调')
      const cursor = event.target.result
      if (cursor) {
        // 获取当前项的时间戳
        const timestamp = cursor.value.date

        // 判断是否是7天前的数据
        if (currentDate - timestamp > 60 * 60 * 1000 * 24 * 7) {
        // if (currentDate - timestamp > 60 * 60) {
          // 删除该项
          store.delete(cursor.primaryKey)
        }

        cursor.continue()
      }
    }
  })
}

/**
 * 删除数据库
 * @param {object} dbName 数据库名称
 */
export function deleteDBAll (dbName) {
  return new Promise((resolve, reject) => {
    const deleteRequest = window.indexedDB.deleteDatabase(dbName)
    deleteRequest.onerror = function (event) {
      console.log('删除失败')
      reject(event)
    }
    deleteRequest.onsuccess = function (event) {
      console.log('删除成功')
      resolve(event)
    }
  })
}
